package com.u8.sdk;

import java.util.ArrayList;
import java.util.List;

import com.u8.sdk.plugin.U8Pay;
import com.u8.sdk.plugin.U8Push;
import com.u8.sdk.plugin.U8Share;
import com.u8.sdk.plugin.U8User;
import com.u8.sdk.verify.U8Verify;
import com.u8.sdk.verify.UToken;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.PushAgent;
import com.umeng.message.UmengRegistrar;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;

public class U8SDK{

	private static final String DEFAULT_PKG_NAME = "com.u8.sdk";
	private static final String APP_PROXY_NAME = "U8_APPLICATION_PROXY_NAME";
	private static final String APP_GAME_NAME = "U8_Game_Application";
	private static final String LOGIC_CHANNEL_PREFIX = "u8channel_";
	
	private static U8SDK instance;
	
	private Application application;
	private Activity context;
	private Handler mainThreadHandler;	
	
	private SDKParams developInfo;
	private Bundle metaData;
	
	private List<IU8SDKListener> listeners;
	
	private List<IActivityCallback> activityCallbacks;
	
	private List<IApplicationListener> applicationListeners;
	
	private String sdkUserID = null;
	private UToken tokenData = null;
	
	private int channel;
	
	
	private U8SDK(){
		mainThreadHandler = new Handler(Looper.getMainLooper());
		listeners = new ArrayList<IU8SDKListener>();
		activityCallbacks = new ArrayList<IActivityCallback>(1);
		applicationListeners = new ArrayList<IApplicationListener>(2);
	}
	
	public static U8SDK getInstance(){
		if(instance == null){
			instance = new U8SDK();
		}
		return instance;
	}
	
	public SDKParams getSDKParams(){
		return developInfo;
	}
	
	public Bundle getMetaData() {
		return metaData;
	}
	
	/**
	 * 推送消息
	 */
	public void pushMsg(){
		final  PushAgent mPushAgent = PushAgent.getInstance(context);
		U8SDK.getInstance().setActivityCallback(new IActivityCallback() {

			@Override
			public void onActivityResult(int requestCode, int resultCode,
					Intent data) {
				
			}

			@Override
			public void onCreate() {
				// TODO Auto-generated method stub
				// TODO Auto-generated method stub
				mPushAgent.enable(new IUmengRegisterCallback() {
					
					@Override
					public void onRegistered(String arg0) {
						
					}
				});
				mPushAgent.onAppStart();
			}

			@Override
			public void onStart() {
				
			}

			@Override
			public void onPause() {
				
			}

			@Override
			public void onResume() {
				
			}

			@Override
			public void onNewIntent(Intent newIntent) {
				
			}

			@Override
			public void onStop() {
				
			}

			@Override
			public void onDestroy() {
				
			}

			@Override
			public void onRestart() {
				
			}

			@Override
			public void onBackPressed() {
				
			}});
		
		
	}
	/**
	 * 获取CPS,CPA,CPD等非SDK联运渠道的逻辑渠道号
	 * @return
	 */
	public int getLogicChannel(){
		
		if(this.channel > 0){
			return this.channel;
		}
		
		String chStr = SDKTools.getLogicChannel(application, LOGIC_CHANNEL_PREFIX);
		if(!TextUtils.isEmpty(chStr)){
			this.channel = Integer.valueOf(chStr);
		}else{
			this.channel = 0;
		}
		
		
		
		return this.channel;
	}
	
	/**
	 * 获取当前SDK对应的渠道号
	 * @return
	 */
	public int getCurrChannel(){
		
		if(this.developInfo == null || !this.developInfo.contains("U8_Channel")){
			return 0;
		}else{
			return this.developInfo.getInt("U8_Channel");
		}
		
	}
	
	public String getCurrChannelName(){
		if(this.developInfo == null || !this.developInfo.contains("U8_ChannelName")){
			return "";
		}
		return this.developInfo.getString("U8_ChannelName");
	}
	
	public String getAppID(){
		if(this.developInfo == null || !this.developInfo.contains("U8_APPID")){
			return "";
		}
		
		return this.developInfo.getString("U8_APPID");
	}
	
	public String getAppKey(){
		if(this.developInfo == null || !this.developInfo.contains("U8_APPKEY")){
			return "";
		}
		
		return this.developInfo.getString("" +
				"");
	}
	
	public void setSDKListener(IU8SDKListener listener){
		if(!listeners.contains(listener) && listener != null){
			this.listeners.add(listener);
		}
	}
	
	public void setActivityCallback(IActivityCallback callback){
		//this.activityCallback = callback;
		if(!this.activityCallbacks.contains(callback) && callback != null){
			this.activityCallbacks.add(callback);
		}
		
	}
	
	public Application getApplication(){
		
		return this.application;
	}
	
	public String getSDKUserID(){
		return this.sdkUserID;
	}
	
	public UToken getUToken(){
		return this.tokenData;
	}
	
	/**
	 * called from onCreate method of Application
	 * @param application
	 */
	public void onAppCreate(Application application){
		this.application = application;
		for(IApplicationListener lis : applicationListeners){
			lis.onProxyCreate();
		}
	}
	
	/**
	 * called from attachBaseContext method of Application
	 * @param application
	 * @param context
	 */
	public void onAppAttachBaseContext(Application application, Context context){
		
		applicationListeners.clear();
		
		PluginFactory.getInstance().loadPluginInfo(context);
		developInfo = PluginFactory.getInstance().getSDKParams(context);
		metaData = PluginFactory.getInstance().getMetaData(context);
		
		IApplicationListener listener1 = newApplicationInstance(application, APP_PROXY_NAME);
		IApplicationListener listener2 = newApplicationInstance(application, APP_GAME_NAME);
		if(listener1 != null){
			applicationListeners.add(listener1);
		}
		if(listener2 != null){
			applicationListeners.add(listener2);
		}
		
		for(IApplicationListener lis : applicationListeners){
			lis.onProxyAttachBaseContext(context);
		}
	}
	
	/**
	 * called from onConfigurationChanged method of Application
	 * @param application
	 * @param newConfig
	 */
	public void onAppConfigurationChanged(Application application, Configuration newConfig){
		for(IApplicationListener lis : applicationListeners){
			lis.onProxyConfigurationChanged(newConfig);
		}
	}
	
	@SuppressWarnings("rawtypes")
	private IApplicationListener newApplicationInstance(Application application, String metaName){
		String proxyAppName = SDKTools.getMetaData(application, metaName);
		
		if(proxyAppName == null || SDKTools.isNullOrEmpty(proxyAppName)){
			return null;
		}
		
		if(proxyAppName.startsWith(".")){
			proxyAppName = DEFAULT_PKG_NAME + proxyAppName;
		}
		
		try {
			Class clazz = Class.forName(proxyAppName);
			return (IApplicationListener)clazz.newInstance();
			
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {

			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		
		
		return null;
	}
	
	/***
	 * 游戏调用抽象层的时候，需要在Activity的onCreate方法中调用该方法
	 * @param context
	 */
	public void init(Activity context){
		this.context = context;
		U8User.getInstance().init();
		U8Pay.getInstance().init();
		U8Push.getInstance().init();
		U8Share.getInstance().init();
	}
	
	public void runOnMainThread(Runnable runnable){
		if(mainThreadHandler != null){
			mainThreadHandler.post(runnable);
			return;
		}
		
		if(context != null){
			context.runOnUiThread(runnable);
		}
	}	
	
	public Activity getContext(){
		return this.context;
	}
	
	public void onResult(int code, String msg){
		
		for(IU8SDKListener listener : listeners){
			listener.onResult(code, msg);
		}
	}
	
	public void onInitResult(InitResult result){
		for(IU8SDKListener listener : listeners){
			listener.onInitResult(result);
		}
	}
	
	public void onLoginResult(LoginResult result){

		for(IU8SDKListener listener : listeners){
			listener.onLoginResult(result);
		}
//		Log.d("U8SDK AuthTask ", "AuthTask");
//		AuthTask authTask = new AuthTask();
//		authTask.execute(result);

	}
	
	public void onSwitchAccount(){
		for(IU8SDKListener listener : listeners){
			listener.onSwitchAccount();
		}
	}
	
	public void onSwitchAccount(LoginResult loginResult){
		for(IU8SDKListener listener : listeners){
			listener.onSwitchAccount(loginResult);
		}
		
		AuthTask authTask = new AuthTask();
		authTask.execute(loginResult);		
	}
	
	public void onLogout(){
		for(IU8SDKListener listener : listeners){
			listener.onLogout();
		}
	}
	
	private void onAuthResult(UToken token){
		
		
		if(token != null && token.isSuc()){
			this.sdkUserID = token.getSdkUserID();
			this.tokenData = token;
		}
		
		if(token == null){
			for(IU8SDKListener listener : listeners){
				listener.onAuthResult(false, 0, "", "");
			}
			
		}else{
			for(IU8SDKListener listener : listeners){
				listener.onAuthResult(token.isSuc(), token.getUserID(), token.getSdkUserID(), token.getToken());
			}
				
		}
	}
	
	public void onPayResult(PayResult result){
		for(IU8SDKListener listener : listeners){
			listener.onPayResult(result);
		}
	}

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(this.activityCallbacks != null){
			for(IActivityCallback callback : this.activityCallbacks){
				callback.onActivityResult(requestCode, resultCode, data);
			}
			
		}
	}
	
	public void onBackPressed(){
		if(this.activityCallbacks != null){
			for(IActivityCallback callback : this.activityCallbacks){
				callback.onBackPressed();	
			}
			
		}
	}

	public void onCreate(){
		if(this.activityCallbacks != null){
			for(IActivityCallback callback : this.activityCallbacks){
				callback.onCreate();
			}
			
		}
	}
	
	public void onStart(){
		if(this.activityCallbacks != null){
			for(IActivityCallback callback : this.activityCallbacks){
				callback.onStart();
			}
		}
	}
	
	public void onPause() {
		if(this.activityCallbacks != null){
			for(IActivityCallback callback : this.activityCallbacks){
				callback.onPause();
			}
			
		}
	}


	public void onResume() {
		
		if(this.activityCallbacks != null){
			for(IActivityCallback callback : this.activityCallbacks){
				callback.onResume();
			}
			
		}
		
	}


	public void onNewIntent(Intent newIntent) {
		if(this.activityCallbacks != null){
			for(IActivityCallback callback : this.activityCallbacks){
				callback.onNewIntent(newIntent);
			}
			
		}
		
	}

	public void onStop() {
		if(this.activityCallbacks != null){
			for(IActivityCallback callback : this.activityCallbacks){
				callback.onStop();
			}
			
		}
		
	}


	public void onDestroy() {
		if(this.activityCallbacks != null){
			for(IActivityCallback callback : this.activityCallbacks){
				callback.onDestroy();
			}
			
		}
		
	}


	public void onRestart() {
		if(this.activityCallbacks != null){
			for(IActivityCallback callback : this.activityCallbacks){
				callback.onRestart();
			}
			
		}
		
	}
	
	class AuthTask extends AsyncTask<LoginResult, Void, UToken>{


		@Override
		protected UToken doInBackground(LoginResult... args) {
			
			LoginResult result = args[0];
			Log.d("UToken doInBackground ", "UToken doInBackground");
			UToken token = U8Verify.auth(result);
			
			return token;
		}
		
		protected void onPostExecute(UToken token){
			
			onAuthResult(token);
		}
		
	}
}
